<template>
  <div class="publish">
    <!-- 标题 -->
    <van-nav-bar @click-left="onClickLeft">
      <template #left>
        <i class="m_fs18 iconfont icon-fanhui"></i>
      </template>
      <template #title>
        <div class="title m_fs18 m_fw">发布</div>
      </template>
    </van-nav-bar>
    <!-- 选中视频 -->
    <div v-if="true" class="m_flex m_fdc m_fjcsb publish_main">
      <div class="m_flex m_faifs intro_video_box">
        <div class="m_f1 intro_box">
          <van-field class="m_fs15 title" v-model="title" placeholder="有标题好易找" />
          <van-field ref="intro" class="m_fs15 intro" v-model="intro" :border="false" rows="3"
            type="textarea" placeholder="有意思的介绍能让更多人看到哦~"/>
          <van-button color="#f1f1f1" size="small" round class="m_fs12 topicBtn"
            type="default" @click="addFriend">@ 好友</van-button>
          <van-button color="#f1f1f1" size="small" round class="m_fs12 topicBtn"
            type="default" @click="addTopic"># 话题</van-button>
        </div>
        <div class="m_pr video_box" @click="previewVideo">
          <video ref="video" class="video" :src="videoUrl"></video>
          <i class="m_fs24 m_tac m_pa m_pb0 m_pl0 m_pr0 iconfont icon-dianji"></i>
        </div>
      </div>
      <div class="m_pr m_flex btn_box" :class="resized?'btn_box2':''">
        <van-button class="m_f1 m_fs18 saveBtn" color="#ccc" round
          @click="cancel">取消</van-button>
        <van-button class="m_f1 m_fs18 publishBtn" color="#008080" round
          @click="publish" :loading="isLoading" loading-text="发布">发布</van-button>
      </div>
    </div>
    <!-- 未选中视频 -->
    <van-empty v-else image="error" description="未选择" />
    <!-- 视频预览 -->
    <van-popup v-model="showPreview">
      <video ref="video2" class="video2" :src="videoUrl" loop></video>
      <div class="menu m_flex m_fjcc m_faic">
        <i class="iconfont icon-fanhui m_fw" @click="fanhui"></i>
        <i class="iconfont" :class="isOn?'icon-24gf-pause2':'icon-bofang'" @click="onPlay"></i>
        <i class="iconfont icon-jietu" @click="cupPicture"></i>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name:'Publish',
  data(){
    return{
      title: '',
      intro:'',
      resized: false,
      showPreview: false,
      isOn: false,
      isLoading: false,
      videoUrl: null,
      coverUrl: null,
      coverFile: null,
    }
  },
  computed:{
    ...mapState('m_video',['videoFile']),
  },
  methods: {
    // 返回
    onClickLeft(){
      this.$router.back()
    },
    // 添加好友
    addFriend(){
      this.intro = this.intro+' @'
      this.$refs.intro.focus()
    },
    // 添加话题
    addTopic(){
      this.intro = this.intro+' #'
      this.$refs.intro.focus()
    },
    // 视频预览
    previewVideo(){
      this.showPreview = !this.showPreview
    },
    // 截取图片
    cutImage(){
      var video
      this.showPreview ? video=this.$refs.video2: video=this.$refs.video
      var canvas = document.createElement('canvas')
      canvas.width = video.videoWidth/2
      canvas.height = video.videoHeight/2
      canvas.getContext('2d').drawImage(video,0,0,canvas.width,canvas.height)
      this.coverUrl = canvas.toDataURL()
      this.coverFile = this.base64ToBlob(this.coverUrl,'image/png')
    },
    // base64转图片
    base64ToBlob(urlData, type) {
      let arr = urlData.split(',');
      let mime = arr[0].match(/:(.*?);/)[1] || type;
      // 去掉url的头，并转化为byte
      let bytes = window.atob(arr[1]);
      // 处理异常,将ascii码小于0的转换为大于0
      let ab = new ArrayBuffer(bytes.length);
      // 生成视图（直接针对内存）：8位无符号整数，长度1个字节
      let ia = new Uint8Array(ab);
      for (let i = 0; i < bytes.length; i++) {
          ia[i] = bytes.charCodeAt(i);
      }
      return new Blob([ab], {
          type: mime
      });
    },
    // 视频播放暂停
    onPlay(){
      var video = this.$refs.video2
      if(video.paused){
        video.play()
        this.isOn = true
      }else{
        video.pause()
        this.isOn = false
      }
    },
    // 截取视频某一帧
    cupPicture(){
      this.cutImage()
      this.$toast('封面图')
    },
    // 发布
    publish(){
      this.isLoading = true
      if(!this.coverFile) this.cutImage()
      var formData = new FormData()
      formData.append('title',this.title)
      formData.append('intro',this.intro)
      formData.append('videoFiles',this.videoFile)
      formData.append('videoFiles',this.coverFile,'image/png')
      this.axios({
        method: 'POST',
        url: 'upload/video',
        data: formData,
        processData: false,
        contentType: false
      }).then(res=>{
        this.isLoading = false
        this.$toast('上传成功')
        this.$router.replace('/my')
      })
    },
    // 保存到草稿
    cancel(){
      this.$router.back()
    },
    // 预览视频返回
    fanhui(){
      this.$refs.video2.pause()
      this.showPreview=!this.showPreview
      this.isOn=false
    }
  },
  mounted(){
    // 软键盘弹出，隐藏按钮
    let height1 = document.documentElement.clientHeight
    window.onresize = ()=>{
      let height2 = document.documentElement.clientHeight
      if(height2 < height1){
        this.resized = true
      }else{
        this.resized = false
      }
    }
    // 视频路径
    if(this.videoFile){
      var blob = new Blob([this.videoFile])
      this.videoUrl = URL.createObjectURL(this.videoFile)
    }
  },
}
</script>

<style lang="scss" scoped>
.publish{
  video{ 
    object-fit: fill;
    display: block;
  }
  .publish_main{ 
    height: calc(100vh - 50px);
    .intro_video_box{
      .intro_box{
        .intro{ height: 76%; }
        .topicBtn{
          color: #242426 !important;
          margin-left: 15px;
        }
      }
      .video_box{
        margin-right: 15px;
        margin-top: 11px;
        .video{
          width: 84px;
          height: 127px;
          border-radius: 5px;
          background: #eee;
        }
        i{
          display: block;
          line-height: 40px;
          color: #fff;
          background: rgba($color: #000000, $alpha: .6);
          border-radius: 0 0 5px 5px;
        }
      }
    }
    .btn_box{
      gap: 10px;
      padding: 20px;
      &.btn_box2{ display: none;}
    }
  }
  // 视频预览弹窗
  .van-popup{
    width: 100vw;
    .video2{ 
      width: 100%;
      max-height: calc(100vh - 60px);
    }
    .menu{
      height: 60px;
      gap: 2px;
      i{
        width: 46px;
        line-height: 46px;
        text-align: center;
        border-radius: 50%;
        color: #fff;
        background: #008080;
        font-size: 20px;
      }
    }
  }
}
</style>